<?php

// phpMyRealty 3
//
// File Name: adduserlistings.php
// File Location : ./
//
// Copyright (c)2009 phpMyRealty.com
//
// e-mail: support@phpMyRealty.com

// Include configuration file and general functions
define('PMR', 'true');

include ( './config.php' );
include ( PATH . '/defaults.php' );

// ----------------------------------------------------------------------
// USER CONTROL PANEL // ADD LISTING

// Title tag content
$title = $conf['website_name_short'] . ' - ' . $lang['Add_Listings'];

$initAjax = TRUE;

include ( PATH . '/includes/ajaxDropdowns.php');

// Template header
include ( PATH . '/templates/' . $cookie_template . '/header.php' );

 // Authenticate user
 // If logged we can start the page output
 if (auth_check($session->fetch('login'), $session->fetch('password')))
  {

   // Fetching the user data
   $sql = 'SELECT * FROM ' . USERS_TABLE . ' WHERE login = "' . $session->fetch('login') . '" LIMIT 1';
   $res = $db->query( $sql );
   $f_res = $db->fetcharray( $res );

   if ($f_res['package'] != '' && $f_res['package'] != '0')
    {
     // Fetch Packages
     $sql = 'SELECT * FROM ' . PACKAGES_AGENT_TABLE  . ' WHERE id = "' . $f_res['package'] . '" LIMIT 1';
     $r_package = $db->query ( $sql );
     $f_package = $db->fetcharray ( $r_package );
    }
   else
    {
     $f_package['listings'] = $conf['free_listings'];
    }

   // End of packages

   // If the Submit button was pressed we start this routine
   if (isset($_POST['submit_listing'])
   && $_POST['submit_listing'] == $lang['Listing_Submit'])
    {

     $form = array();

     // Change checkbox arrays into a string, with ':' as a separator
     if (isset($_POST['buildings']) && is_array($_POST['buildings'])) $_POST['buildings'] = implode (':', $_POST['buildings']); else $_POST['buildings'] = '';
     if (isset($_POST['appliances']) && is_array($_POST['appliances'])) $_POST['appliances'] = implode (':', $_POST['appliances']); else $_POST['appliances'] = '';
     if (isset($_POST['features']) && is_array($_POST['features'])) $_POST['features'] = implode (':', $_POST['features']); else $_POST['features'] = '';

     // If display_address was not checked we assign NO as value
     // instead of empty one
     if (!isset($_POST['display_address'])) $_POST['display_address'] = 'NO';

     // safehtml() all the POST variables
     // to insert into the database or
     // print the form again if errors
     // found
     $form = array_map('safehtml', $_POST);

     // Cut the decription size if there was a JS problem
     // or JS is disabled
     $form['description'] = substr ($form['description'], 0, $conf['listing_description_size']);

     // Printing the Information table header
     // to output errors or confirmaion messages
     echo table_header ( $lang['Information'] );

     // Initially we think that no errors were found
     $count_error = 0;

     // Check for the empty or incorrect required fields

     if (
      (isset($form['location1']) && $form['location1'] == 'ANY') ||
      (isset($form['location2']) && $form['location2'] == 'ANY') ||
      (isset($form['location3']) && $form['location3'] == 'ANY')
     ) {
      echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Location'] . '</span><br />'; $count_error++;
     }

     if (empty($form['title']) || strlen($form['title']) < 4 )
      { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Listing_Title'] . '</span><br />'; $count_error++;}

     if ((!empty($form['bathrooms'])) && !eregi('^[0-9]+$', $form['bathrooms']))
      { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Listing_Bathrooms'] . '</span><br />'; $count_error++;}

     if ((!empty($form['half_bathrooms'])) && !eregi('^[0-9]+$', $form['half_bathrooms']))
      { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Listing_Half_Bathrooms'] . '</span><br />'; $count_error++;}

     if ((!empty($form['bedrooms'])) && !eregi('^[0-9]+$', $form['bedrooms']))
      { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Listing_Bedrooms'] . '</span><br />'; $count_error++;}

     if ((!empty($form['year_built'])) && !eregi('^[0-9]+$', $form['year_built']))
      { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Listing_Year_Built'] . '</span><br />'; $count_error++;}

     if ((!empty($form['price'])) && !eregi('^[0-9]+$', $form['price']))
      { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Listing_Price'] . '</span><br />'; $count_error++;}

     if ((!empty($form['status'])) && !eregi('^[0-9]+$', $form['status']))
      { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Listing_Status'] . '</span><br />'; $count_error++;}

     // Check if this user have reached the maximum
     // number of possible listings set by admin
     $sql = 'SELECT * FROM ' . PROPERTIES_TABLE . ' WHERE userid = "' . $f_res['id'] . '" ';
     $r = $db->query($sql) or error ('Critical Error', mysql_error () );

     if ($db->numrows($r) >= $f_package['listings'])
      { echo $lang['Maximum_Number_Of_Listings_Reached'] . '<br />'; $count_error++;}

     // Check if this listing title is already exist
     if (strcasecmp($conf['allow_same_title'], 'ON')) {
         $sql = 'SELECT title FROM ' . PROPERTIES_TABLE . ' WHERE title = "' . $form['title'] . '" ';
         $r = $db->query($sql) or error ('Critical Error', mysql_error () );

         if ($db->fetcharray($r) > 0 )
          { echo $lang['Title_Used'] . '<br />'; $count_error++;}
     }

     // Check if this email is already used
     if (strcasecmp($conf['allow_same_e_mail'], 'ON')) {
         $sql = 'SELECT id FROM ' . USERS_TABLE . ' WHERE email = "' . $form['realtor_e_mail'] . '"';
         $r = $db->query($sql) or error ('Critical Error', mysql_error () );

         if ($db->fetcharray($r) > 0 )
          { echo $lang['Email_Used'] . '<br />'; $count_error++;}
     }

     //

     // If there were any errors found we start printing them out
     if ($count_error > 0)
      echo '<br /><span class="warning">' . $lang['Errors_Found'] . ': ' . $count_error . '</span><br />';

     // If no errors were found during the above checks we continue
     if ($count_error == 0)
      {
       // Update user details in the database

       // Get the user IP address
       $user_ip = $_SERVER['REMOTE_ADDR'];
       // If there is more than one IP
       // get the first one from the
       // comma separated list
       if ( strstr($user_ip, ', ') )
        {
         $ips = explode(', ', $user_ip);
         $user_ip = $ips[0];
        }

       // If listing needs to be approved by the administrator
       if ($conf['approve_listings'] == 'ON') {
        $approved = 0;
        $approved_date = 'NULL';
       } else {
        $approved = 1;
        $approved_date = 'NOW()';
       }

       if (!isset($form['location1'])) $form['location1'] = '0';
       if (!isset($form['location2'])) $form['location2'] = '0';
       if (!isset($form['location3'])) $form['location3'] = '0';
       
       // Add custom value if text input field
       $custom_fields = array(
       					'custom1' => $form['custom1'],
       					'custom2' => $form['custom2'],
       					'custom3' => $form['custom3'],
       					'custom4' => $form['custom4'],
       					'custom5' => $form['custom5'],
       					'custom6' => $form['custom6'],
       					'custom7' => $form['custom7'],
       					'custom8' => $form['custom8'],
       					'custom9' => $form['custom9'],
       					'custom10' => $form['custom10'],
       );
       foreach ( $custom_fields AS $key => $value )
       {
       		if ( $value != '' )
       		{
       			// Check if this is an input field
       			$sql = "SELECT id, type FROM " . FIELDS_TABLE . " WHERE field = '" . $key . "' ";
       			$r = $db->query( $sql ) or error( 'Critical Error', mysql_error() );
       			$f = $db->fetcharray( $r );
       			if ( $f['type'] == 'input' )
       			{      				
       				// Override value of this custom input box with the primary key of the VALUES table
       				$form[$key] = '{INPUT}' . $value;
       			}
       		}
       }

       // Create a mysql query
        $sql = 'INSERT INTO '. PROPERTIES_TABLE .
        ' (userid, approved, mls, type, style, title, title2, title3, title4, title5,
			title6, title7, title8, title9, title10, title11, title12, title13, title14, title15,
			title16, title17, title18, title19, title20, title21, title22, title23, title24, title25, title26,
           title27, title28, title29, title30, description, description2,
           description3, description4, description5, description6, description7,
           description8, description9, description10, description11,
           description12, description13, description14, description15,
           description16, description17, description18, description19,
           description20, description21, description22, description23,
           description24, description25, description26, description27,
           description28, description29, description30, size, dimensions,
           bathrooms, half_bathrooms, bedrooms, location2, zip, address1,
           address2, display_address, price, directions, year_built, buildings,
           appliances, features, garage, garage_cars, basement, date_added,
           ip_added, type2, video, calendar, latitude, longitude, status,
           custom1, custom2, custom3, custom4, custom5, custom6, custom7,
           custom8, custom9, custom10, date_approved )
          VALUES (
			"' . $f_res['id'] . '",
			"' . $approved . '" ,
			"' . @$form['mls'] . '",
			"' . $form['type'] . '",
			"' . $form['style'] . '",
	 		"' . $form['title']. '",
			"' . $form['title2'] . '",
			"' . $form['title3'] . '",
			"' . $form['title4'] . '",
			"' . $form['title5'] . '",
			"' . $form['title6'] . '",
			"' . $form['title7'] . '",
			"' . $form['title8'] . '",
			"' . $form['title9'] . '",
			"' . $form['title10'] . '",
			"' . $form['title11'] . '",
			"' . $form['title12'] . '",
			"' . $form['title13'] . '",
			"' . $form['title14'] . '",
			"' . $form['title15'] . '",
			"' . $form['title16'] . '",
			"' . $form['title17'] . '",
			"' . $form['title18'] . '",
			"' . $form['title19'] . '",
			"' . $form['title20'] . '",
			"' . $form['title21'] . '",
			"' . $form['title22'] . '",
			"' . $form['title23'] . '",
			"' . $form['title24'] . '",
			"' . $form['title25'] . '",
			"' . $form['title26'] . '",
			"' . $form['title27'] . '",
			"' . $form['title28'] . '",
			"' . $form['title29'] . '",
			"' . $form['title30'] . '",
	 		"' . $form['description'] . '",
			"' . $form['description2'] . '",
			"' . $form['description3'] . '",
			"' . $form['description4'] . '",
			"' . $form['description5'] . '",
			"' . $form['description6'] . '",
			"' . $form['description7'] . '",
			"' . $form['description8'] . '",
			"' . $form['description9'] . '",
			"' . $form['description10'] . '",
			"' . $form['description11'] . '",
			"' . $form['description12'] . '",
			"' . $form['description13'] . '",
			"' . $form['description14'] . '",
			"' . $form['description15'] . '",
			"' . $form['description16'] . '",
			"' . $form['description17'] . '",
			"' . $form['description18'] . '",
			"' . $form['description19'] . '",
			"' . $form['description20'] . '",
			"' . $form['description21'] . '",
			"' . $form['description22'] . '",
			"' . $form['description23'] . '",
			"' . $form['description24'] . '",
			"' . $form['description25'] . '",
			"' . $form['description26'] . '",
			"' . $form['description27'] . '",
			"' . $form['description28'] . '",
			"' . $form['description29'] . '",
			"' . $form['description30'] . '",
	 		"' . $form['size'] . '",
	 		"' . $form['dimensions'] . '",
	 		"' . $form['bathrooms'] . '",
	 		"' . $form['half_bathrooms'] . '",
	 		"' . $form['bedrooms'] . '",
	 		"' . $form['location1'] . '#' . $form['location2'] . '#' . $form['location3'] . '",
	 		"' . @$form['zip'] . '",
	 		"' . $form['address1'] . '",
	 		"' . $form['address2'] . '",
	 		"' . $form['display_address'] . '",
	 		"' . $form['price'] . '",
	 		"' . $form['directions'] . '",
	 		"' . $form['year_built'] . '",
	 		"' . $form['buildings'] . '",
	 		"' . $form['appliances'] . '",
	 		"' . $form['features'] . '",
	 		"' . $form['garage'] . '",
	 		"' . $form['garage_cars'] . '",
	 		"' . $form['basement'] . '",
	 		"' . date('Y-m-d') . '",
	 		"' . $user_ip . '",
	 		"' . $form['type2'] . '",
	 		"' . $form['video'] . '",
	 		"' . $form['calendar'] . '",
	 		"' . $form['latitude'] . '",
	 		"' . $form['longitude'] . '",
	 		"' . $form['status'] . '",
			"' . $form['custom1'] . '",
			"' . $form['custom2'] . '",
			"' . $form['custom3'] . '",
			"' . $form['custom4'] . '",
			"' . $form['custom5'] . '",
			"' . $form['custom6'] . '",
			"' . $form['custom7'] . '",
			"' . $form['custom8'] . '",
			"' . $form['custom9'] . '",
			"' . $form['custom10'] . '",
	 		' . $approved_date . '
	 	)';

        $db->query($sql) or error ('Critical Error', mysql_error ());

        // Fetch the last auto incremented listing id
        $id = mysql_insert_id();

	    // If uploading a video
	    if (isset($_FILES['video_file']))
	     {

			// If MEncoder is enabled, convert it
			if ($conf['mencoder'] == 'ON')
			{

		      $raw_video_path = $_FILES['video_file']['tmp_name'];
		      $new_flv = PATH . '/video/' . $id . '.flv';

		      $mencoder_cmd = $conf['path_to_mencoder'] . ' ' . $raw_video_path . ' -o ' . $new_flv . ' -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=800:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames -vf scale=450:400 -srate 22050';
		      @exec($mencoder_cmd . ' 2>&1', $output);

		      if (!file_exists($new_flv)) {
		      $mencoder_cmd = $conf['path_to_mencoder'] . ' ' . $raw_video_path . ' -o ' . $new_flv . ' -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=800:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames -vop scale=450:400 -srate 22050';
		      @exec($mencoder_cmd . ' 2>&1', $output);
		      }

		      if (!file_exists($new_flv)) {
		      $mencoder_cmd = $conf['path_to_mencoder'] . ' ' . $raw_video_path . ' -o ' . $new_flv . ' -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=800:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -vf scale=450:400 -srate 22050';
		      @exec($mencoder_cmd . ' 2>&1', $output);
		      }

				if ( file_exists( $raw_video_path ) )
				{
		      		@unlink($raw_video_path);
				}

				if (file_exists(PATH . '/video/' . $id . '.flv'))
					$video_uploaded = TRUE;
				else
					$video_uploaded = FALSE;

			}
			else
			{

				// Make sure this is an FLV, if so copy it
				$ext = end(explode('.', $_FILES['video_file']['name']));

				if ($ext == 'flv')
				{
					if (copy($_FILES['video_file']['tmp_name'], PATH . '/video/' . $id . '.flv'))
						$video_uploaded	= TRUE;
					else
						$video_uploaded	= FALSE;
				}

			}

	     }

        if ($_FILES['image_file']['tmp_name'] != '')
         {

          // We think that the image is uploaded or will
          // return FALSE if the upload_image function
          // will fail
          $uploaded = TRUE;

          // Upload and resize the image
          upload_image ( 'images', $id, $_FILES['image_file']['tmp_name'], $conf['image_resampled_width'] ) or $uploaded = FALSE;

         }

	// If do not need admin approval we
	// add this new listing into the category
        if ($conf['approve_listings'] != 'ON')
         update_categories ('' , $form['type']);

	// Output the 'Thank you' message
	if ($conf['approve_listings'] == 'ON')
         {

	  echo $lang['Realtor_Listing_Added_Approve'];

	  $mail = new PHPMailer();

          if(PHPMAILER == '3') {
 	   $mail->IsSMTP(); // set mailer to use SMTP
 	   $mail->Host = $smtp['host'];  // specify main and backup server
	   $mail->SMTPAuth = true;     // turn on SMTP authentication
	   $mail->Username = $smtp['login'];  // SMTP username
	   $mail->Password = $smtp['password']; // SMTP password
          }
          elseif(PHPMAILER == '2') {
 	   $mail->IsSendmail(); // set mailer to use SMTP
          }
	  else {
          }

	  $mail->From = $conf['general_e_mail'];
	  $mail->FromName = $conf['general_e_mail_name'];
	  $mail->AddAddress($conf['general_e_mail']);

	  $mail->Subject = $lang['Admin_Listing_Notification_Subject'];

          // Replacing the variable names
	  $lang['Admin_Listing_Notification_Mail'] = str_replace('{title}', $form['title'], $lang['Admin_Listing_Notification_Mail']);

	  $mail->MsgHTML = $lang['Admin_Listing_Notification_Mail'];
	  $mail->AltBody = removehtml($lang['Admin_Listing_Notification_Mail']);

	  $mail->Send();

         }
	else

         {
	  echo $lang['Realtor_Listing_Added'];

          // Send email alerts to all subscribers

          $r = $db->query ('SELECT * FROM ' . ALERTS_TABLE . ' WHERE
                            type = "' . $form['type'] . '" AND
			    city = "' . $form['location1'] . '#' . $form['location2'] . '#' . $form['location3'] . '" AND
			    zip = "' . @$form['zip'] . '" AND
			    approved = 1');

          while ($f = $db->fetcharray($r))
           {

            $temp_alert = $lang['Alert_Mail'];

	    $mail = new PHPMailer();

          if(PHPMAILER == '3') {
		 	   $mail->IsSMTP(); // set mailer to use SMTP
		 	   $mail->Host = $smtp['host'];  // specify main and backup server
			   $mail->SMTPAuth = true;     // turn on SMTP authentication
			   $mail->Username = $smtp['login'];  // SMTP username
			   $mail->Password = $smtp['password']; // SMTP password
          }
          elseif(PHPMAILER == '2') {
 			   $mail->IsSendmail(); // set mailer to use SMTP
          }

	    $mail->From = $conf['general_e_mail'];
	    $mail->FromName = $conf['general_e_mail_name'];
	    $mail->AddAddress($f['email']);

	    $mail->WordWrap = 50;                                 // set word wrap to 50 characters
	    $mail->IsHTML(true);                                  // set email format to HTML

            $lang['Alert_Subject'] = str_replace('{website}', $conf['website_name'], $lang['Alert_Subject']);

	    $mail->Subject = $lang['Alert_Subject'];

            // Replacing the variable names
            $temp_alert = str_replace('{name}', $f['name'], $temp_alert);
            $temp_alert = str_replace('{link}', URL . '/viewlisting.php?id=' . $id, $temp_alert);
            $temp_alert = str_replace('{unsubscribe}', URL . '/alertscontrol.php?req=unsubscribe&code=' . $f['code'], $temp_alert);
            $temp_alert = str_replace('{website}', $conf['website_name'], $temp_alert);

	    $mail->Body    = $temp_alert;
	    $mail->AltBody = removehtml($temp_alert);

	    $mail->Send();

           }

         }

      }

    // Video upload status
    if (isset($video_uploaded) && $video_uploaded == TRUE)
     echo '<p><b>' . $lang['Video_OK'] . '</b>';

    if (isset($video_uploaded) && $video_uploaded == FALSE)
     echo '<p><b>' . $lang['Video_BAD'] . '</b>';

     echo table_footer ( );

    }

   // Navigation Menu
   echo table_header ( $lang['Menu_User_Login'] );
   echo ' <table cellpadding="5" cellspacing="0" border="0"> <tr>';
   // Go To Edit Listings Form

   // Fetching the listings number from the table
   $sql = 'SELECT id FROM ' . PROPERTIES_TABLE . ' WHERE userid = "' . $f_res['id'] . '"';
   $r_listings = $db->query( $sql );
   $res_listings = $db->numrows( $r_listings );

   // If we've got more than 0 listings we print out the
   // link
   if ($res_listings > 0)
    echo '<td width="80" align="center" valign="top"><a href="' . URL . '/viewuserlistings.php"><img src="' . URL . '/templates/' . $cookie_template . '/images/icons/editlistings.png" border="0" alt=""><br />' . $lang['Edit_Listings'] . '</a> (' . $res_listings . ') </td>';

   // Back To User Control Panel
   echo '<td width="80" align="center" valign="top"><a href="' . URL . '/login.php"><img src="' . URL . '/templates/' . $cookie_template . '/images/icons/login.png" border="0" alt=""><br />' . $lang['Menu_User_Login'] . '</a></td>';
   echo ' </tr></table> ';
   echo table_footer();

   //

   // Main form

   // Submit Listing Form Table Header
   echo table_header ( $lang['Menu_Submit_Property'] );

   // Define the form variables if the form was not updated
   // or the previous data submission had no errors
   if (!isset($form) || (isset($count_error) && $count_error == '0'))
    {
     $form = array();

     $first = preg_split('//', $f_res['first_name'], -1, PREG_SPLIT_NO_EMPTY);
     $last = preg_split('//', $f_res['last_name'], -1, PREG_SPLIT_NO_EMPTY);

     $form['mls'] = strtoupper($first[0] . $last[0] . rand(100000, 999999));

	$form['title'] = '';
	$form['title2']  = '';
	$form['title3']  = '';
	$form['title4']  = '';
	$form['title5']  = '';
	$form['title6']  = '';
	$form['title7']  = '';
	$form['title8']  = '';
	$form['title9']  = '';
	$form['title10']  = '';
	$form['title11']  = '';
	$form['title12']  = '';
	$form['title13']  = '';
	$form['title14']  = '';
	$form['title15']  = '';
	$form['title16']  = '';
	$form['title17']  = '';
	$form['title18']  = '';
	$form['title19']  = '';
	$form['title20']  = '';
	$form['title21']  = '';
	$form['title22']  = '';
	$form['title23']  = '';
	$form['title24']  = '';
	$form['title25']  = '';
	$form['title26']  = '';
	$form['title27']  = '';
	$form['title28']  = '';
	$form['title29']  = '';
	$form['title30']  = '';
	$form['description']  = '';
	$form['description2']  = '';
	$form['description3']  = '';
	$form['description4']  = '';
	$form['description5']  = '';
	$form['description6']  = '';
	$form['description7']  = '';
	$form['description8']  = '';
	$form['description9']  = '';
	$form['description10']  = '';
	$form['description11']  = '';
	$form['description12']  = '';
	$form['description13']  = '';
	$form['description14']  = '';
	$form['description15']  = '';
	$form['description16']  = '';
	$form['description17']  = '';
	$form['description18']  = '';
	$form['description19']  = '';
	$form['description20']  = '';
	$form['description21']  = '';
	$form['description22']  = '';
	$form['description23']  = '';
	$form['description24']  = '';
	$form['description25']  = '';
	$form['description26']  = '';
	$form['description27']  = '';
	$form['description28']  = '';
	$form['description29']  = '';
	$form['description30']  = '';
	$form['type'] = '';
	$form['style'] = '';
	$form['size'] = '';
	$form['dimensions'] = '';
	$form['bathrooms'] = '0';
	$form['half_bathrooms'] = '0';
	$form['bedrooms'] = '0';
	$form['location2'] = '';
	$form['zip'] = '';
	$form['address1'] = '';
	$form['address2'] = '';
	$form['display_address'] = 'YES';
	$form['price'] = '0';
	$form['directions'] = '';
	$form['year_built'] = '';
	$form['buildings'] = '';
	$form['appliances'] = '';
	$form['features'] = '';
	$form['basement'] = '';
	$form['garage'] = '';
	$form['garage_cars'] = '0';
	$form['type2'] = '';
	$form['video'] = '';
	$form['calendar'] = '';
	$form['latitude'] = '';
	$form['longitude'] = '';
	$form['status'] = '';
    $form['custom1'] = '';
    $form['custom2'] = '';
    $form['custom3'] = '';
    $form['custom4'] = '';
    $form['custom5'] = '';
    $form['custom6'] = '';
    $form['custom7'] = '';
    $form['custom8'] = '';
    $form['custom9'] = '';
    $form['custom10'] = '';
    }

   // Output the form
   echo '
    <form action="' . URL . '/adduserlistings.php" method="POST" enctype="multipart/form-data" name="form">
     <table width="100%" cellpadding="5" cellspacing="0" border="0">
	';

    if (empty($iso_language_codes[$cookie_language])) {
        $_fckCalendarLang = 'en';
    } else {
        $_fckCalendarLang = $iso_language_codes[$cookie_language];
    }
    
   echo userform ($lang['Listing_Image_File'], '<input type="file" name="image_file" maxlength="50" class="formSubmitInput">');
   echo userform ($lang['Module_Listing_Type'], '<select name="type2" class="formSubmitSelect">' . generate_options_list(TYPES2_TABLE, $form['type2']) . '</select>', '1');
   echo userform ($lang['Listing_Status'], '<select name="status" class="formEditSelect">' . generate_options_list(STATUS_TABLE, $form['status']) . '</select>', '1');
   if (strcasecmp(@$conf['show_mls'], 'OFF') != 0) {
       echo userform ($lang['Listing_MLS'], '<input type="text" name="mls" value="' . $form['mls'] . '" maxlength="10" class="formSubmitInput">');
   }

	// Show all available languages
	$num = 1;
	foreach ($installed_languages AS $language1 => $key1)
	{
		$key1 = str_replace( 'name', 'title', $key1 );
		$title_html .= '<a href="javascript:void(0);" onclick="jQuery(\'#' . $key1 . '\').show();">' . ucwords($language1) . '</a>&nbsp;&nbsp;';
		if ($num % 8 == 0)
			$title_html .= '<br />';
		$num++;
	}

	// Display text boxes for every language
	$num = 1;
	foreach ($installed_languages AS $language1 => $key1)
	{
		// Grab the right text for each textarea
		$strip = str_replace( 'name', 'title', $key1 );
		$key1 = str_replace( 'name', 'title', $key1 );

		if ($num == 1)
			$display = 'normal';
		else
			$display = 'none';

		$title_html .= '
		<div style="display: ' . $display . ';" id="' . $key1 . '">
		<input type="text" size="100" maxlength="255" name="' . $key1 . '" id="' . $key1 . '" class="formSubmitInput" value="' . $form[$strip] . '">
		<br /><a href="javascript:void(0);" onclick="jQuery(\'#' . $key1 . '\').hide();">Hide ' . ucwords($language1) . '</a>
		</div>
		';

		$num++;
	}

   echo userform ($lang['Listing_Title'], $title_html, '1');

   echo userform ($lang['Listing_Property_Type'], '<select name="type" class="formSubmitInput">' . generate_options_list(TYPES_TABLE, $form['type']) . '</select>', '1');
   echo userform ($lang['Listing_Style'], '<select name="style" class="formSubmitSelect">' . generate_options_list(STYLES_TABLE, $form['style']) . '</select>', '1');

	// Show all available languages
	$num = 1;
	foreach ($installed_languages AS $language1 => $key1)
	{
		// Grab the right text for each textarea
		$key1 = str_replace( 'name', 'description', $key1 );
		$description_html .= '<a href="javascript:void(0);" onclick="jQuery(\'#' . $key1 . '\').show();">' . ucwords($language1) . '</a>&nbsp;&nbsp;';
		if ($num % 8 == 0)
			$description_html .= '<br />';
		$num++;
	}

	// Display text boxes for every language
	$num = 1;
	foreach ($installed_languages AS $language1 => $key1)
	{
		// Grab the right text for each textarea
		$strip = str_replace( 'name', 'description', $key1 );
		$key1 = str_replace( 'name', 'description', $key1 );

		if ($num == 1)
			$display = 'normal';
		else
			$display = 'none';

		$description_html .= '
		<div style="display: ' . $display . ';" id="' . $key1 . '">
		<textarea class="ckeditor" cols="100" rows="20" class="formSubmitArea" name="' . $key1 . '" id="' . $key1 . '">' . $form[$strip] . '</textarea>
		<br /><a href="javascript:void(0);" onclick="jQuery(\'#' . $key1 . '\').hide();">Hide ' . ucwords($language1) . '</a>
		</div>
		';

		$num++;
	}

   echo userform ($lang['Listing_Description'], $description_html, '1');

   echo userform ($lang['Listing_Lot_Size'], '<input type="text" name="size" value="' . $form['size'] . '" maxlength="50" class="formSubmitInput">');
   echo userform ($lang['Listing_Dimensions'], '<input type="text" name="dimensions" value="' . $form['dimensions'] . '" maxlength="50" class="formSubmitInput">');
   echo userform ($lang['Listing_Bathrooms'], '<input type="text" name="bathrooms" value="' . $form['bathrooms'] . '" maxlength="2" class="formSubmitInput">');
   echo userform ($lang['Listing_Half_Bathrooms'], '<input type="text" name="half_bathrooms" value="' . $form['half_bathrooms'] . '" maxlength="2" class="formSubmitInput">');
   echo userform ($lang['Listing_Bedrooms'], '<input type="text" name="bedrooms" value="' . $form['bedrooms'] . '" maxlength="2" class="formSubmitInput">');

// ==

  $r_location1 = $db->query('SELECT selector, category FROM ' . LOCATION1_TABLE . ' ORDER by category ASC');

  $newContentMain = '<option value="ANY">' . $lang['Select'] . '</option>' . "\n";

  while ($f_location1 = $db->fetcharray($r_location1)) {
   $newContentMain.= '<option value="' . $f_location1['selector'] . '">' . $f_location1['category'] . '</option>' . "/n";
  }

  echo userform ($lang['Location'], '
          <select name="location1" class="span3" id="location1" onchange="xajax_fetchLocations2(this.value);">

' . $newContentMain . '

          </select>
          <div style="display: inline" id="location2div" name="location2div"></div>
          <div style="display: inline" id="location3div" name="location3div"></div>
', '1');

// ==

  if (strcasecmp(@$conf['show_postal_code'], 'OFF') != 0) {
      echo userform ($lang['Zip_Code'], '<input type="text" name="zip" value="' . $form['zip'] . '" maxlength="20" class="formSubmitInput">');
  }
   echo userform ($lang['Listing_Address1'], '<input type="text" name="address1" value="' . $form['address1'] . '" maxlength="50" class="formSubmitInput">');
   echo userform ($lang['Listing_Address2'], '<input type="text" name="address2" value="' . $form['address2'] . '" maxlength="50" class="formSubmitInput">');

   if (isset($form['display_address']) && $form['display_address'] == 'YES') $display_address_checked = 'CHECKED'; else $display_address_checked = '';
    echo userform ($lang['Listing_Display_Address'], '<input type="checkbox" name="display_address" value="YES" ' . $display_address_checked . '>');

   echo userform ($lang['Listing_Latitude'], '<input type="text" name="latitude" value="' . $form['latitude'] . '" maxlength="50" id="latbox" class="formSubmitInput">');
   echo userform ($lang['Listing_Longitude'], '<input type="text" name="longitude" value="' . $form['longitude'] . '" maxlength="50" id="lonbox" class="formSubmitInput">');

   echo userform ($lang['Listing_Price'], '<input type="text" name="price" value="' . $form['price'] . '" maxlength="13" class="formSubmitInput">');
   echo userform ($lang['Listing_Directions'], '<textarea class="ckeditor" wrap="soft" cols="45" rows="4"  name="directions" onKeyDown="textCounter(this.form.directions,this.form.listing_directions_counter, ' . $conf['listing_directions_size'] . ');" onKeyUp="textCounter(this.form.directions,this.form.listing_directions_counter, ' . $conf['listing_directions_size'] . ');" class="formSubmitArea">' . unsafehtml($form['directions']) . '</textarea>');
   echo userform ('', '<input readonly type="text" name="listing_directions_counter" size="5" maxlength="5" value="' . $conf['listing_directions_size'] . '" class="formSubmitInput"> ' . $lang['Characters_Left']);
   echo userform ($lang['Listing_Year_Built'], '<input type="text" name="year_built" value="' . $form['year_built'] . '" maxlength="4" class="formSubmitInput">');

   // Some variables needs to be set
   // if their value is empty
   if (!isset($form['buildings']))
    $form['buildings'] = '';

   if (!isset($form['appliances']))
    $form['appliances'] = '';

   if (!isset($form['features']))
    $form['features'] = '';

   echo userform ($lang['Listing_Additional_Out_Buildings'], generate_checkbox_list(BUILDINGS_TABLE, 'buildings', explode(':', $form['buildings'])));
   echo userform ($lang['Listing_Appliances_Included'], generate_checkbox_list(APPLIANCES_TABLE, 'appliances', explode(':', $form['appliances'])));
   echo userform ($lang['Listing_Features'], generate_checkbox_list(FEATURES_TABLE, 'features', explode(':', $form['features'])));
   echo userform ($lang['Listing_Garage'], '<select name="garage" class="formSubmitSelect">' . generate_options_list(GARAGE_TABLE, $form['garage']) . '</select>');
   echo userform ($lang['Listing_Garage_Cars'], '<input type="text" name="garage_cars" value="' . $form['garage_cars'] . '" maxlength="2" class="formSubmitInput">');
   echo userform ($lang['Listing_Basement'], '<select name="basement" class="formSubmitSelect">' . generate_options_list(BASEMENT_TABLE, $form['basement']) . '</select>');
   echo userform ($lang['Video_Tour'], '<input type="text" size="45" name="video" value="' . $form['video'] . '" maxlength="255">');
   echo userform ($lang['Video_Upload_File'], '<input type="file" size="40" name="video_file" maxlength="50">');

	// Custom fields
	$query = "SELECT * FROM " . FIELDS_TABLE . " ORDER BY name ASC";
	$result = $db->query($query) OR error( 'Critical Error:' . $query);
	if ($db->numrows($result) > 0) {
		while($row = $db->fetcharray($result)) {
			// Type of input
			if ($row['type'] != '') {
				if ($row['type'] == 'input') {
					echo userform ($row['name'], '<input type="text" name="' . $row['field'] . '" class="formSubmitInput">');
				} elseif ($row['type'] == 'select') {
					// Grab all options for this select
					$options = "SELECT * FROM " . VALUES_TABLE . " WHERE f_id = '" . addslashes($row['id']) . "'";
					$get_options = $db->query($options) OR error( 'Critical Error:' . $options);
					if ($db->numrows($get_options) > 0) {
						while($row2 = $db->fetcharray($get_options)) {
							$option_list .= "<option value=\"" . $row2['id'] . "\">" . $row2['name'] . "</option>";
						}
						echo userform ($row['name'], '<select name="' . $row['field'] . '" class="formSubmitSelect"><option value="">Please Select</option>' . $option_list . '</select>');
					}
				}
			}
		}
	}

	// Show availability calendar if enabled
	if ($conf['show_calendar'] == 'ON')
	{

        echo '<tr id="calendarBox"><td colspan="2" align="center">

    <p><b><u>' . $lang['Availability_Calendar'] . '</u></b></p>';

        $dates = explode(',', $form['calendar']);
        foreach ($dates as $k => $date) {
            if (strlen(trim($date)) == 0) {
                unset($dates[$k]);
                continue;
            }
            list($month, $day, $year) = explode('/');
            if (date('Y-m-d') > $year.'-'.$month.'-'.$day) {
                unset($dates[$k]);
            }
        }
        $form['calendar'] = implode(',', $dates);
        if ($form['calendar']) {
            $form['calendar'] .= ',';
        }

        echo '
    <textarea name="calendar" id="calendar_output" style="display:none;">' . unsafehtml($form['calendar']) . '</textarea>
    <input type="hidden" name="dateTemp" id="dateTemp" value="" />
    <div id="calendar-container"></div>

    <script type="text/javascript">
    function dateAvailable(y, m, d) {
        m = (++m < 10) ? "0" + m : m;
        d = (d < 10) ? "0" + d : d;
        return document.getElementById("calendar_output").value.indexOf("" + m + "/" + d + "/" + y + ",");
    }

    function toggleDateAvailable(cal) {
        var storage = document.getElementById("calendar_output");
        var d = document.getElementById("dateTemp").value + ",";
        var dateParts = document.getElementById("dateTemp").value.split("/");
        var date = new Date(dateParts[2], dateParts[0] - 1, dateParts[1]);
        var list = storage.value;
        var pos = list.indexOf(d);
        if (pos >= 0) {
            if (list.length == 11) {
                storage.value = "";
            } else if (pos == 0) {
                storage.value = list.substring(pos + 11);
            } else {
                storage.value = list.substring(0, pos) + list.substring(pos + 11);
            }
       } else {
            storage.value += d;
       }
       cal._init(cal.firstDayOfWeek, date);
    }

    var today = new Date();
    today.setHours(0, 0, 0 ,0);
    Calendar.setup(
      {
        flat         : "calendar-container", // ID of the parent element
        dateStatusFunc : function(date, y, m, d) {
                           if (date < today) {
                            return true;
                           } else if (dateAvailable(y, m, d) >= 0) {
                            return "special";
                           }
                           return false;
                         },
          inputField  : "dateTemp",
          ifFormat    : "%m/%d/%Y",
          weekNumbers : false,
          onUpdate    : function (cal) {
            if (cal.dateClicked) {
                toggleDateAvailable(cal);
            }
          },
          range : new Array('.date('Y').', '.(date('Y') + 1).')
       }
    );
    </script>
    ';

        echo '
    <script type="text/javasscript">
    (function($){
        $(document).ready(function () {
            $("#calendarBox").show();
        });
    })(jQuery);
    </script>
    <div id="calendar-legend">
        <p class="calendarAvailable"><span>'.$lang['Availability_Calendar_Vacancy'].'</span></p>
        <p class="calendarUnavailable"><span>'.$lang['Availability_Calendar_No_Vacancy'].'</span></p>
    </div>

    </td></tr>';
   }

   echo userform ('', '<input type="Submit" class="submit" name="submit_listing" value="' . $lang['Listing_Submit'] . '">');

   echo '
    </table>
   </form>
   ';

   echo table_footer ();

  }

 else

  {

  error ('Critical Error' , 'Please, login to access this script.');

  }

// Template footer
include ( PATH . '/templates/' . $cookie_template . '/footer.php' );

?>